package com.free.chat.filter;

import cn.dev33.satoken.exception.*;
import com.free.chat.entity.ApiResult;
import com.free.chat.exception.ApiException;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;
import org.noear.solon.validation.annotation.Logined;

/**
 * solon官方提供的一个全局异常过滤器
 */
@Component
public class ValidatorFailureFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (ApiException e) {
            ctx.render(ApiResult.error(e.getMessage()));
        } catch (ValidatorException e) {
            if (e.getAnnotation() instanceof Logined) {
                ctx.render(ApiResult.unAuthorization());
            }
        } catch (SaTokenException e) {
            if (e instanceof NotLoginException) {    // 如果是未登录异常
                // NotLoginException ee = (NotLoginException) e;
                ctx.render(ApiResult.unAuthorization());
            } else if (e instanceof NotRoleException) {        // 如果是角色异常
                NotRoleException ee = (NotRoleException) e;
                ctx.render(ApiResult.error("无此角色：" + ee.getRole()));
            } else if (e instanceof NotPermissionException) {    // 如果是权限异常
                NotPermissionException ee = (NotPermissionException) e;
                ctx.render(ApiResult.error("无此权限：" + ee.getPermission()));
            } else if (e instanceof DisableServiceException) {    // 如果是被封禁异常
                DisableServiceException ee = (DisableServiceException) e;
                ctx.render(ApiResult.error("账号被封禁：" + ee.getDisableTime() + "秒后解封"));
            } else {    // 普通异常, 输出：500 + 异常信息
                ctx.render(ApiResult.error(e.getMessage()));
            }
        }
    }
}
